package flexo.file.reader;

import java.io.BufferedReader;

import flexo.file.Node;


/**
 * Reads a config text file and loads into memory.
 *
 * The file must have the following layout:
 *
 * [section1]
 * variable1=value1
 * variable2=calue2
 *
 * [section2]
 * variable3=value3
 * ...
 */
public class Config extends Reader
{
	protected int l = 0;

	public void read(Node fileNode)
	{
		Node lastNode = null;

		try
		{			
			BufferedReader br = this.getBufferedReader(fileNode);
			
			while (br.ready())
			{
				++l;
				String line;
				line = br.readLine();

				int ssPos = line.indexOf('[');
				// Section
				if (ssPos >= 0)
				{
					int sePos = line.lastIndexOf("]");
					String section = line.substring(ssPos+1,sePos-(ssPos+1));
					lastNode = new Node(section);
					fileNode.addChild(lastNode);
				}
				// Property
				else
				{
					int eqPos = line.indexOf("=");

					if (eqPos >= 0)
					{
						String name = line.substring(0,eqPos);
						String value = line.substring(eqPos+1,line.length()-1-eqPos);
						if (lastNode != null)
						{
							lastNode.setProperty(name,value);
						}
					}
				}
			}
			
			br.close();
		}
		catch (Exception e)
		{
			formatError(fileNode.name,l);
		}		
	}
}